package com.lemon.core.log.log4j.util;

import com.alibaba.fastjson.JSON;
import com.lemon.core.common.lang.util.DateUtils;
import com.lemon.core.log.log4j.bean.BaseLogEnum;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy;
import org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author lottery
 * @ClassName LemonLogUtils
 * @desc 日志工具类
 * @Date 2018/11/3 13:40
 * @Version 1.0
 **/
public class LemonLogUtils {

    private static LoggerContext ctx = (LoggerContext) LogManager.getContext(false);

    private static Configuration config = ctx.getConfiguration();

    /**
     * 获取Logger
     * @param logEnum
     * @return
     */
    private static Logger getLogger(BaseLogEnum logEnum) {
        if (!config.getLoggers().containsKey(logEnum.getLogName())) {
            synchronized (config) {
                if (!config.getLoggers().containsKey(logEnum.getLogName())) {
                    initConfig(logEnum);
                }
            }
        }
        return LogManager.getLogger(logEnum.getLogName());
    }

    /**
     * 动态初始化logger
     * @param logEnum
     */
    private static void initConfig(BaseLogEnum logEnum) {
        //创建一个展示的样式：PatternLayout，   还有其他的日志打印样式。
        Layout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%m%n").build();

        TimeBasedTriggeringPolicy tbtp = TimeBasedTriggeringPolicy.createPolicy(null, null);

        DefaultRolloverStrategy strategy = DefaultRolloverStrategy
                .createStrategy(null, null, null, null, null, false, config);

        RollingFileAppender.Builder builder = RollingFileAppender.newBuilder()
                .withFileName(logEnum.getFilePath() + ".log")
                .withFilePattern(logEnum.getFilePath() + ".log.%d{yyyy-MM-dd}")
                .withAppend(true)
                .withStrategy(strategy)
                .withPolicy(tbtp);

        RollingFileAppender.Builder builder1 = (RollingFileAppender.Builder) builder.withName(logEnum.getLogName());
        RollingFileAppender.Builder builder2 = (RollingFileAppender.Builder) builder1.withLayout(layout);
        RollingFileAppender appender = builder2.build();
        appender.start();
        config.addAppender(appender);

        AppenderRef ref = AppenderRef.createAppenderRef(logEnum.getLogName(), null, null);
        AppenderRef[] refs = new AppenderRef[]{ref};
        LoggerConfig loggerConfig = LoggerConfig.createLogger(false,
                Level.ALL, logEnum.getLogName(), "true", refs, null, config, null);
        loggerConfig.addAppender(appender, null, null);

        config.addLogger(logEnum.getLogName(), loggerConfig);
        ctx.updateLoggers();
    }

    public static void printInfo(BaseLogEnum logEnum, Object... infos) {
        Logger logger = getLogger(logEnum);
        StringBuffer log = new StringBuffer();
        log.append(DateUtils.getCurrentTime()).append("\t");
        for (Object info : infos) {
            log.append(JSON.toJSONString(info) + "\t");
        }
        logger.info(log.deleteCharAt(log.length() - 1));
    }

    public static void printObjProps(BaseLogEnum logEnum, Object object, String... props) {
        printObjProps(logEnum,null, object, props);
    }

    /**
     * 打印类日志
     * @param logEnum       日志配置常量
     * @param commonParams  对象
     * @param object
     * @param props         需打印属性 需要对象的GET方法来获取属性
     */
    public static void printObjProps(BaseLogEnum logEnum, Object commonParams, Object object, String... props) {
        Logger logger = getLogger(logEnum);
        StringBuffer log = new StringBuffer();
        log.append(DateUtils.getCurrentTime()).append("\t");
        log.append(buildPublicParams(commonParams));
        if (props != null) {
            for (String property : props) {
                try {
                    log.append(object.getClass().getMethod("get" + getMethodName(property)).invoke(object)).append("\t");
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info(log.deleteCharAt(log.length() - 1));
    }

    public static void printObj(BaseLogEnum logEnum, Object object) {
        printObj(logEnum, null, object);
    }

    /**
     * 打印类日志
     * @param logEnum       日志配置常量
     * @param commonParams
     * @param object        对象
     */
    public static void printObj(BaseLogEnum logEnum, Object commonParams, Object object) {
        Logger logger = getLogger(logEnum);
        StringBuffer log = new StringBuffer();
        log.append(DateUtils.getCurrentTime()).append("\t");
        log.append(buildPublicParams(commonParams));

        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        StringBuilder objLog = new StringBuilder();
        for (Field field : fields) {
            try {
                objLog.append(clazz.getMethod("get" + getMethodName(field.getName())).invoke(object)).append("\t");
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        log.append(objLog);
        logger.info(log.deleteCharAt(log.length() - 1));
    }

    public static void printObjAndProps(BaseLogEnum logEnum, Object object, String... props) {
        printObjAndProps(logEnum, null, object, props);
    }

    /**
     * 打印类日志
     * @param logEnum
     * @param commonParams
     * @param object
     * @param props
     */
    public static void printObjAndProps(BaseLogEnum logEnum, Object commonParams, Object object, String... props) {
        Logger logger = getLogger(logEnum);
        StringBuffer log = new StringBuffer();
        log.append(DateUtils.getCurrentTime()).append("\t");
        log.append(buildPublicParams(commonParams));

        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        StringBuilder objLog = new StringBuilder();

        for (Field field : fields) {
            try {
                objLog.append(clazz.getMethod("get" + getMethodName(field.getName())).invoke(object)).append("\t");
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        log.append(objLog);
        if (props != null) {
            for (String property : props) {
                log.append(property).append("\t");
            }
        }

        logger.info(log.deleteCharAt(log.length() - 1));
    }

    public static void printMap(BaseLogEnum logEnum, LinkedHashMap<String, Object> linkedHashMap) {
        printMap(logEnum, null, linkedHashMap);
    }


    /**
     * 打印Map日志
     * @param logEnum
     * @param commonParams
     * @param linkedHashMap
     */
    public static void printMap(BaseLogEnum logEnum, Object commonParams, LinkedHashMap<String, Object> linkedHashMap) {
        Logger logger = getLogger(logEnum);
        StringBuffer log = new StringBuffer();
        log.append(DateUtils.getCurrentTime()).append("\t");
        log.append(buildPublicParams(commonParams));
        if (linkedHashMap != null) {
            for (Map.Entry<String, Object> entry : linkedHashMap.entrySet()) {
                log.append(entry.getValue()).append("\t");
            }
        }
        logger.info(log.deleteCharAt(log.length() - 1));
    }

    public static void printCustomProps(BaseLogEnum logEnum, String... props) {
        printCustomProps(logEnum, null, props);
    }

    /**
     * 打印自定义参数日志
     *
     * @param logEnum 日志配置常量
     * @param props   需打印的参数数组
     */

    public static void printCustomProps(BaseLogEnum logEnum, Object commonParams, String... props) {
        Logger logger = getLogger(logEnum);
        StringBuilder log = new StringBuilder();
        log.append(DateUtils.getCurrentTime()).append("\t");
        log.append(buildPublicParams(commonParams));
        if (props != null) {
            for (String property : props) {
                log.append(property).append("\t");
            }
        }
        logger.info(log.deleteCharAt(log.length() - 1));
    }

    private static String getMethodName(String fieldName) {
        byte[] items = fieldName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }


    private static String buildPublicParams(Object commonParams) {
        if (commonParams != null) {
            Class clazz = commonParams.getClass();
            Field[] fields = clazz.getDeclaredFields();
            StringBuilder commonLog = new StringBuilder();
            for (Field field : fields) {
                try {
                    commonLog.append(clazz.getMethod("get" + getMethodName(field.getName())).invoke(commonParams)).append("\t");
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
            return commonLog.toString();
        }
        return "";
    }
}
